<template>
    <div id='myApp'>
        <Row style="margin-bottom: 40px;border-bottom: 1px solid #eeeeee;">
            <Col span="7" style="border-bottom:2px solid #2d8cf0 ;padding: 0 0 8px 18px;">
            <span style="color: #2d8cf0;">
                <Icon type="md-add-circle" />&nbsp;&nbsp;
                <span style="color: black;">网站管理&nbsp;&nbsp;>&nbsp;&nbsp;API列表&nbsp;&nbsp;>&nbsp;</span>测试API
            </span>
            </Col>
        </Row>
        <Row>
            <Col span="12" offset="4">
                <Form v-model="parametersForm" :label-width="180">
                    <FormItem label="API名称：">
                        {{currentDetail.name}}
                    </FormItem>
                    <FormItem label="API地址：">
                        {{currentDetail.url}}
                    </FormItem>
                    <FormItem label="HTTP请求方式：">
                        {{currentDetail.httpMethod}}
                    </FormItem>
                    <FormItem label="请求参数：">
                        <!-- <Row style="margin-bottom: 10px;">
                            <Col span="7">
                            <span style="float: right;">
                                apiKey
                            </span>
                            </Col>
                            <Col span="16" offset="1">
                                <span style="float: left;">
                                    <Input disabled v-model="currentApikey" />
                                </span>
                                
                            </Col>
                        </Row>
                        <Row style="margin-bottom: 10px;">
                            <Col span="7">
                            <span style="float: right;">
                                sign
                            </span>
                            </Col>
                            <Col span="16" offset="1">
                                <span style="float: left;">
                                    <Input disabled v-model="currentApikey" />
                                </span>
                                
                            </Col>
                        </Row> -->

                        <Row v-for="(item,index) in parameters" :key="index" style="margin-bottom: 10px;">
                            <Col span="7">
                            <span style="float: right;">
                                {{item.label}}
                            </span>
                            </Col>
                            <Col span="16" offset="1">
                                <span style="float: left;">
                                    <input :ref="item.ref" :name="item.label" class="res_ipt" />
                                </span>
                                
                            </Col>
                        </Row>
                        
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="saveTest" style="width: 100px;">测试</Button>
                    </FormItem>
                </Form>                
            </Col>
        </Row>
        <div class='json_content' v-if="responseStatus==true">
	        <div class="res_h1">
                <div class="h1_tit">响应内容：</div>
                <div class="h1-btn">
                    <Button type="default" size="small" v-clipboard:copy="responseContentString" v-clipboard:success="onCopy" v-clipboard:error="onError">复制内容</Button>
                </div>
            </div>
	        <div class="res_con">
				<json-view :data="responseContent"/>                        
	        </div>
        </div>
    </div>
</template>
<style type="text/css">
	.res_con .json-view-container{background-color:#f6f8fa!important; }
</style>
<style scoped>
.res_h1{
    font-weight: bold;
    margin-bottom: 10px;
    display: flex;
    -webkit-display:flex;
}
.res_h1 .h1-btn{
    margin-left: auto;
    width: 100px;
    flex:0 0 100px;
    text-align: right;
}
.res_ipt{
    display: inline-block;
    width: 100%;
    min-height: 32px;
    max-height: 96px;
    line-height: 1.5;
    padding: 4px 7px;
    font-size: 14px;
    border: 1px solid #dcdee2;
    border-radius: 4px;
    color: #515a6e;
    background-color: #fff;
    background-image: none;
    position: relative;
    cursor: text;
}
.res_con2{
    max-height: 500px;
    overflow: auto;
}
</style>
<script>
    import md5 from 'js-md5';
    import { mapState, mapActions } from 'vuex'
    import zmitiUtil from '../../../lib/util'
    import jsonView from 'vue-json-views'
    export default {
        computed: mapState({
            Authorization: state => state.Authorization
        }),
        data() {
            return {
                isEdit: '',
                currentDetail:{},
                parameters:[],
                parametersForm:[],
                responseContent:{},
                responseContentString:'',
                currentApikey:'',
                currendCheckcode:'',
                md5string:{
                    url:'',
                    parameters:[],
                    userName:'',
                    apiKey:'',
                    checkCode:''
                },
                responseStatus:false
            }
        },
        components: {
            jsonView
        },
        mounted() {
            this.getDetail()
        },
        created(){
          
        },
        methods: {
            onCopy (e) {//复制成功
             this.$Message.success("内容已复制到剪切板！")
            },            
            onError (e) {// 复制失败时的回调函数
             this.$Message.error("抱歉，复制失败！")
            },
            getDetail() {//根据id查询站点详细内容，然后填充到页面上 
                var _this = this;                
                var path='apiweb/view';
                var postData = {
                    id:this.$route.params.id
                }
                zmitiUtil.Ajax(path,postData).then(res => {
                    var data = res.data;
                    _this.currentDetail = res.data;
                    console.log(_this.currentDetail,'_this.currentDetail')
                    data.parameters.map((item,index)=>{
                        _this.parameters.push({
                            label:item,
                            ref:'parametersForm'
                        })

                        _this.$set(_this.parametersForm,item,'');
                    })
                    console.log(_this.parameters,'_this.parameters');
                    console.log(_this.parametersForm,'_this.parametersForm');
                     _this.md5string.url=res.data.url;//md5中的url
                    _this.getApiKey(res.data.name);//获取当前的APIkey
                }).catch((error) => {
                    console.log(error,'error');
                });
            },
            saveTest(){
                var _this = this;
                _this.parameters.sort();
                console.log(_this.parameters,'_this.parameters');
                /*获取ref名字为parametersForm的input值*/
                let formInput={};
                let paramarr=[];
                let paramObj={};
                _this.parameters.forEach((item,index)=>{
                    //console.log(item,'parameters-',index)
                    let iptval = this.$refs.parametersForm[index].value;
                    let inputname = this.$refs.parametersForm[index].name;
                    _this.$set(formInput,inputname,iptval);//请求表单parameters的值
                    _this.$set(paramObj,inputname,iptval);//拼接前的parameters
                })
                console.log(formInput,'parameters中所有参数');
                /*
                *结果：
                *{minA: "qqq", maxA: "wwww", ruleB: "eeee", source: "rrrrr"}
                */

                /*将parameters所有参数的索引与值合并为一个字符串,并用下划线连接,构建为新的数组*/
                for (let i in paramObj){
                    paramarr.push(i+'_'+paramObj[i]);
                }
                console.log(paramarr,'拼接后的parameters数组');
                /*
                *结果：
                *["minA_qqq", "maxA_wwww", "ruleB_eeee", "source_rrrrr"]
                */

                /*将paramarr所有参数与值合并为一个字符串，并用冒号隔开*/
                _this.md5string.parameters=paramarr.join(':');
                //console.log(_this.md5string,'拼接前的md5对象');
                /*
                *结果
                *minA_zzz:maxA_xxxx:ruleB_ddd:source_ffff
                */

                /**
                将所有需要md5的值合并为一个新数组
                **/
                let md5Arr=[];
                for(let i in _this.md5string){
                    md5Arr.push(_this.md5string[i]);
                }
                //console.log(md5Arr,'md5值的数组');
                /*
                *结果：
                *["subTitleImg", "minA_qqq:maxA_www:ruleB_eeee:source_rrrr", "yangfan", "ql8ZU0NsirixlvkgozFR4rG0zbVMl9dyT", "tNLRMhIWdrIdYJ66C"]
                */

                /*将所有需要md5提交的值合并为一个字符串，并用冒号隔开*/
                let position_title='';
                position_title=md5Arr.join(':');
                console.log(position_title,'md5前的字符串');
                /*
                *结果：
                *subTitleImg:minA_zzz:maxA_xxxx:ruleB_ddd:source_ffff:yangfan:ql8ZU0NsirixlvkgozFR4rG0zbVMl9dyT:tNLRMhIWdrIdYJ66C
                */

                let signstr='';
                signstr=md5(position_title).toUpperCase();
                console.log(signstr,'md5的值');

                var path='api/invoke/'+_this.currentDetail.url;
                var postData = formInput;
                if(_this.currentApikey!='' && _this.currendCheckcode!=''){
                    /*添加apiKey和sign*/
                    postData.apiKey=_this.currentApikey
                    postData.sign=signstr
                }
                
                console.log(postData,'测试时提交的参数')
                zmitiUtil.Ajax(path,postData).then(res => {
                    var data = res.data;
                    console.log(data,'获取响应模板');
                    _this.responseStatus=true;//显示响应内容
                    setTimeout(()=>{
                    	/*给json-views赋值*/                    	
                   		_this.responseContent=res.data;
                        _this.responseContentString=JSON.stringify(res.data);//将响应内容转为字符串
                    },300)
                }).catch((error) => {
                    console.log(error,'error');
                });
            },
            getApiKey(apiName){//列出apiName获取当前Api的Key
                var _this = this;                
                var path='apikey/list';
                var postData = {
                    enabled:true,
                    apiName
                };
                zmitiUtil.Ajax(path,postData).then(res => {
                    var data = res.data;
                    
                    if(res.data.total>0){
                        console.log(res.data,'APIkey获取成功');
                        _this.currentApikey=res.data.results[0].key;
                        _this.currendCheckcode=res.data.results[0].checkCode;                        
                        
                        _this.md5string.userName=res.data.results[0].userName;
                        _this.md5string.apiKey=res.data.results[0].key;
                        _this.md5string.checkCode=res.data.results[0].checkCode;
                    }else{
                        
                    }
                    
                }).catch((error) => {
                    console.log(error,'error');
                });
            },
            
        }
    }
</script>